package me.spring.cloud.common.components.mds.util;

import me.spring.cloud.common.components.mds.exception.DynamicDataSourceException;
import me.spring.cloud.common.components.mds.exception.code.DyDataSourceCode;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class DataSourceSet {

  private static final ThreadLocal<String> contextHolder = new ThreadLocal();

  private static List<String> dataSourceKeyList = new CopyOnWriteArrayList<String>();

  private static Map targetDataSourcesMap = new ConcurrentHashMap();

  public static Object putTargetDataSourcesMap(Object key, Object dataSource) {
    dataSourceKeyList.add(key.toString());
    return targetDataSourcesMap.put(key, dataSource);
  }

  public static Object removeTargetDataSourcesMap(Object key) {
    try {
      dataSourceKeyList.remove(key);
      return targetDataSourcesMap.remove(key);
    } catch (Exception e) {
      log.error(e.getMessage(), e);
      throw new DynamicDataSourceException(DyDataSourceCode.DataSource303);
    }
  }

  public static Map getTargetDataSourcesMap() {
    return targetDataSourcesMap;
  }

  public static void setCurrDataSource(String ds) {
    contextHolder.set(ds);
  }

  public static String getCurrDataSource() {
    return contextHolder.get();
  }

  public static void clearCurrDataSource() {
    contextHolder.remove();
  }

  public static boolean containsDataSource(String dataSourceKey) {
    return dataSourceKeyList.contains(dataSourceKey);
  }
}
